/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mb.product.ui;

import com.mb.main.AppManager;
import com.mb.other.bean.Category;
import com.mb.other.bean.Size;
import com.mb.other.bean.Trademark;
import com.mb.product.bean.Product;
import com.mb.product.bean.ProductDetail;
import com.mb.product.dao.ProductDAO;
import com.mb.product.dao.ProductDetailDAO;
import com.mb.utils.MyBusinessUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author ldanh
 */
public class ProductFormDialog extends javax.swing.JDialog {
    
    private AppManager app;
    private DefaultComboBoxModel<Category> cbModelCategory;
    private DefaultComboBoxModel<Trademark> cbModelTrademark;
    private boolean isEdit = false;
    /**
     * Creates new form AddProductDialog
     */
    public ProductFormDialog(java.awt.Frame parent, boolean modal, AppManager app, Product product) {
        super(parent, modal);
        this.app = app;
        setTitle("Thêm sản phẩm mới");
        initComponents();
        cbModelCategory = new DefaultComboBoxModel<Category>(this.app.mapCategoryToArray());
        cbModelTrademark = new DefaultComboBoxModel<Trademark>(this.app.mapTrademarkToArray());
        cbCategory.setModel(cbModelCategory);
        cbTrademark.setModel(cbModelTrademark);
        
        if (product != null) {
            setTitle("Sửa thông tin");
            btOk.setText("Sửa");
            isEdit = true;
            tfProductId.setEnabled(false);
            initDataForm(product);
        }
    }
    
    private void initDataForm(Product product) {
        tfProductId.setText(product.getProductId());
        tfProductName.setText(product.getProductName());
        Category category = app.getMapCategory().get(product.getCategoryId());
        cbCategory.setSelectedItem(category);
        Trademark trademark = app.getMapTrademark().get(product.getTrademarkId());
        cbTrademark.setSelectedItem(trademark);
        taColorDesc.setText(product.getProductColorDesc());
        tfPriceOrg.setText(MyBusinessUtils.formatDecimalString(String.valueOf(product.getProductPriceOrg()), false));
        tfPrice.setText(MyBusinessUtils.formatDecimalString(String.valueOf(product.getProductPrice()), false));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbProductId = new javax.swing.JLabel();
        tfProductId = new javax.swing.JTextField();
        lbProductName = new javax.swing.JLabel();
        tfProductName = new javax.swing.JTextField();
        lbCategory = new javax.swing.JLabel();
        cbCategory = new javax.swing.JComboBox();
        lbTrademark = new javax.swing.JLabel();
        cbTrademark = new javax.swing.JComboBox();
        lbColorDesc = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taColorDesc = new javax.swing.JTextArea();
        lbPriceOrg = new javax.swing.JLabel();
        tfPriceOrg = new javax.swing.JTextField();
        lbPrice = new javax.swing.JLabel();
        tfPrice = new javax.swing.JTextField();
        btOk = new javax.swing.JButton();
        btCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lbProductId.setText("Mã:");

        lbProductName.setText("Tên:");

        lbCategory.setText("Loại:");

        cbCategory.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        lbTrademark.setText("Hãng:");

        cbTrademark.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        lbColorDesc.setText("Mô tả màu:");

        taColorDesc.setColumns(20);
        taColorDesc.setRows(5);
        jScrollPane1.setViewportView(taColorDesc);

        lbPriceOrg.setText("Giá nhập vào:");

        lbPrice.setText("Giá bán ra:");

        btOk.setText("Thêm");
        btOk.setPreferredSize(new java.awt.Dimension(70, 23));
        btOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btOkActionPerformed(evt);
            }
        });

        btCancel.setText("Hủy bỏ");
        btCancel.setPreferredSize(new java.awt.Dimension(70, 23));
        btCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGap(19, 19, 19)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(lbCategory, javax.swing.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
                                        .addComponent(lbProductId, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(lbProductName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(layout.createSequentialGroup()
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                .addComponent(tfProductId)
                                                .addComponent(tfProductName, javax.swing.GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)))
                                        .addGroup(layout.createSequentialGroup()
                                            .addGap(3, 3, 3)
                                            .addComponent(cbCategory, 0, 314, Short.MAX_VALUE))))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(lbTrademark, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(cbTrademark, javax.swing.GroupLayout.PREFERRED_SIZE, 314, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(lbColorDesc, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 352, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(lbPriceOrg)
                                        .addComponent(lbPrice))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(tfPriceOrg)
                                        .addComponent(tfPrice, javax.swing.GroupLayout.DEFAULT_SIZE, 268, Short.MAX_VALUE))))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(122, 122, 122)
                        .addComponent(btOk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbProductId)
                    .addComponent(tfProductId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbProductName)
                    .addComponent(tfProductName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbCategory)
                    .addComponent(cbCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbTrademark)
                    .addComponent(cbTrademark, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(lbColorDesc)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbPriceOrg)
                    .addComponent(tfPriceOrg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbPrice)
                    .addComponent(tfPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btOk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btCancelActionPerformed

    private void btOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btOkActionPerformed
        // TODO add your handling code here:
        boolean validate = validateForm();
        if (validate) {
            Product product = new Product();
            product.setProductId(tfProductId.getText());
            product.setProductName(tfProductName.getText());
            product.setCategoryId(((Category)cbCategory.getSelectedItem()).getCategoryId());
            product.setTrademarkId(((Trademark)cbTrademark.getSelectedItem()).getTrademarkId());
            product.setProductColorDesc(taColorDesc.getText());
            product.setProductPriceOrg(Float.valueOf(tfPriceOrg.getText()));
            product.setProductPrice(Float.valueOf(tfPrice.getText()));
            ProductDAO dao = new ProductDAO();
            if (isEdit) {
                if (dao.update(product)) {
                    JOptionPane.showMessageDialog(this, "Sửa thông tin thành công", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
                    app.reloadData();
                    this.dispose();
                }
            } else {
                if (dao.addNew(product)) {
                    Map<Integer, Size> mapSize = app.getMapSize();
                    List<ProductDetail> listProductDetail = new ArrayList<ProductDetail>();
                    for (Integer sizeId : mapSize.keySet()) {
                        listProductDetail.add(new ProductDetail(product.getProductId(), sizeId, 0));
                    }
                    ProductDetailDAO detailDao = new ProductDetailDAO();
                    detailDao.addAll(listProductDetail);

                    JOptionPane.showMessageDialog(this, "Thêm sản phẩm thành công", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
                    app.reloadData();
                    this.dispose();
                }
            }
        }
    }//GEN-LAST:event_btOkActionPerformed

    private boolean validateForm() {
        String message = "";
        if (tfProductId.getText().isEmpty()) {
            message += "- Chưa nhập " + lbProductId.getText().replace(":", "") + "\n" ;
        } else if (!isEdit && app.getMapProduct().containsKey(tfProductId.getText())){
            message += "- " + lbProductId.getText().replace(":", "") + " đã tồn tại\n" ;
        }
        if (tfProductName.getText().isEmpty()) {
            message += "- Chưa nhập " + lbProductName.getText().replace(":", "") + "\n";
        }
        if (taColorDesc.getText().isEmpty()) {
            message += "- Chưa nhập " + lbColorDesc.getText().replace(":", "") + "\n";
        }
        if (tfPriceOrg.getText().isEmpty()) {
            message += "- Chưa nhập " + lbPriceOrg.getText().replace(":", "") + "\n";
        } else if (!MyBusinessUtils.checkStringIsDigit(tfPriceOrg.getText())) {
            message += "- " + lbPriceOrg.getText().replace(":", "") + " phải là số\n";
        }
        if (tfPrice.getText().isEmpty()) {
            message += "- Chưa nhập " + lbPrice.getText().replace(":", "") + "\n";
        } else if (!MyBusinessUtils.checkStringIsDigit(tfPrice.getText())) {
            message += "- " + lbPrice.getText().replace(":", "") + " phải là số\n";
        }
        
        if (!message.isEmpty()) {
            JOptionPane.showMessageDialog(this, message, "Lỗi", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        return true;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancel;
    private javax.swing.JButton btOk;
    private javax.swing.JComboBox cbCategory;
    private javax.swing.JComboBox cbTrademark;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbCategory;
    private javax.swing.JLabel lbColorDesc;
    private javax.swing.JLabel lbPrice;
    private javax.swing.JLabel lbPriceOrg;
    private javax.swing.JLabel lbProductId;
    private javax.swing.JLabel lbProductName;
    private javax.swing.JLabel lbTrademark;
    private javax.swing.JTextArea taColorDesc;
    private javax.swing.JTextField tfPrice;
    private javax.swing.JTextField tfPriceOrg;
    private javax.swing.JTextField tfProductId;
    private javax.swing.JTextField tfProductName;
    // End of variables declaration//GEN-END:variables
}
